package logic

import (
	"whale/internal/app/admin/consts/req"
	"whale/internal/app/admin/consts/res"
	"whale/internal/app/admin/errors"
	"whale/internal/app/admin/model"
	"whale/internal/repository"
	"whale/pkg/utils"
)

// generate logic *RoleLogic IRoleLogic
type IRoleLogic interface {
	// 权限列表
	GetList(data req.RoleListReq) (interface{}, error)
	// 权限详情
	GetInfo(id int) (interface{}, error)
	// 创建权限
	Create(data req.RoleCreateReq) error
	// 更新权限
	Update(data req.RoleUpdatgeReq) error
	// 更新状态
	Set(data req.SetDataReq) error
	// 删除广告
	Deleted(id int) error
}

// 更新状态
func (logic *RoleLogic) Set(data req.SetDataReq) error {
	if ok := utils.ContainsKeyInSlice(data.Value, []string{"status", "sort"}); ok {
		return errors.ContainsKeyError()
	}
	if err := logic.Repository.Table(&model.AdminAuth{}).Where("id = ?", data.Id).Update(data.Value); err != nil {
		return errors.DBStoreError()
	}
	return nil
}

// 权限列表
func (logic *RoleLogic) GetList(data req.RoleListReq) (interface{}, error) {
	var list res.RoleListRes

	dataBase := logic.Repository.Table(&model.AdminAuth{}).LikeSearch([]string{"title"}, data.Keyword).Eq("status", data.Status)

	if err := dataBase.Paging(data.Page, data.PageSize).OrderBy("id desc").GetList(&list); err != nil {
		return nil, errors.DBReadError()
	}
	return list, nil
}

// 广告详情
func (logic *RoleLogic) GetInfo(id int) (interface{}, error) {
	var info res.RoleInfoRes
	if _, err := logic.Repository.Table(&model.AdminAuth{}).Where("id = ?", id).Get(&info); err != nil {
		return nil, errors.DBReadError()
	}
	return info, nil
}

// 创建广告
func (logic *RoleLogic) Create(data req.RoleCreateReq) error {
	var roleData model.AdminAuth

	if err := utils.StructCopy(&roleData, &data); err != nil {
		return errors.StructCopyError()
	}

	if err := logic.Repository.Table(&model.AdminAuth{}).Insert(&roleData); err != nil {
		return errors.DBStoreError()
	}
	return nil
}

// 更新广告
func (logic *RoleLogic) Update(data req.RoleUpdatgeReq) error {
	var roleData model.AdminAuth

	if err := utils.StructCopy(&roleData, &data); err != nil {
		return errors.StructCopyError()
	}

	if err := logic.Repository.Table(&model.AdminAuth{}).Where("id = ?", data.Id).Update(&roleData); err != nil {
		return errors.DBStoreError()
	}
	return nil
}

// 删除广告
func (logic *RoleLogic) Deleted(id int) error {
	if err := logic.Repository.Table(&model.AdminAuth{}).Where("id = ?", id).Deleted(); err != nil {
		return errors.DBStoreError()
	}
	return nil
}

type RoleLogic struct {
	Repository repository.IRepository `bean:"Repository"`
}
